package cn.hxzy.office.filte;

import cn.hxzy.office.EndWith;
import cn.hxzy.office.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author little black
 */
public class FirstInterceptor implements HandlerInterceptor {
    /**
     * 该方法在目标方法之前被调用.
     * 若返回值为 true, 则继续调用后续的拦截器和目标方法.
     * 若返回值为 false, 则不会再调用后续的拦截器和目标方法.
     * 可以考虑做权限. 日志, 事务等.
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse, Object handler) throws Exception {
        String uri = httpServletRequest.getRequestURI();
        User user = (User) httpServletRequest.getSession().getAttribute("loginUser");
        if (user != null) {
            if (user.getRoleId() == 0) {
                return true;
            } else {
                if (uri.endsWith(EndWith.userIndex.name()) || uri.endsWith(EndWith.createUserSchedule.name()) || uri.endsWith(EndWith.saveUserSchedule.name()) || uri.endsWith(EndWith.deleteUserSchedule.name()) || uri.endsWith(EndWith.updateUserSchedule.name()) ||
                        uri.endsWith(EndWith.editUserSchedule.name()) || uri.endsWith(EndWith.searchUserSchedule.name()) || uri.endsWith(EndWith.searchMyDoc.name()) || uri.endsWith(EndWith.searchNewsInfo.name())|| uri.endsWith(EndWith.logout.name())) {
                    return true;
                }
            }
            httpServletResponse.sendRedirect(EndWith.userIndex.name());
        }
        httpServletResponse.sendRedirect(EndWith.login.name());
        return false;
    }

    /**
     * 调用目标方法之后, 但渲染视图之前.
     * 可以对请求域中的属性或视图做出修改.
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("[FirstInterceptor] postHandle");
    }

    /**
     * 渲染视图之后被调用. 释放资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("[FirstInterceptor] afterCompletion");
    }

}